<template>
  <el-dropdown @command="handleCommand">
    <span class="el-dropdown-link">
      下拉菜单
      <i class="el-icon-arrow-down el-icon--right"></i>
    </span>
    <el-dropdown-menu slot="dropdown">
      <el-dropdown-item v-for="(item, index) in dataTrigger" :key="index" :command="item.name">{{
        item.label
      }}</el-dropdown-item>
    </el-dropdown-menu>
  </el-dropdown>
</template>

<script>
export default {
  name: 'CDropdown',
  props: {
    props: {
      type: Array,
      default: function() {
        return [
          {
            fields: []
          }
        ]
      }
    }
  },
  data() {
    return {
      activeName: ''
    }
  },
  computed: {
    dataTrigger() {
      if (this.props[1].fields[0].value.dataJson.json) {
        const result = this.props[1].fields[0].value.dataJson.json
        // console.log(this.getResult(result))
        return this.getResult(result)
      }
      return []
    },
    itemWidth() {
      if (this.dataTrigger.length > 1) {
        return 100 / this.dataTrigger.length
      } else {
        return 100
      }
    }
  },
  methods: {
    handleCommand(command) {
      //
      this.$message('click on item ' + command)
    },
    getResult(json) {
      let jsonArray = []
      try {
        jsonArray = JSON.parse(json)
      } catch (e) {
        console.warn(e.message)
      }
      const model = this.props[1].fields[0].value.dataJson.model
      const fieldHref = model[0].field
      const mappingHref = model[0].mapping
      const keyHref = mappingHref || fieldHref

      const fieldTitle = model[1].field
      const mappingTitle = model[1].mapping
      const keyTitle = mappingTitle || fieldTitle

      if (jsonArray.length > 0) {
        const outJson = []
        jsonArray.forEach(element => {
          outJson.push({
            name: element[keyHref],
            label: element[keyTitle]
          })
        })
        return outJson
      } else {
        return jsonArray
      }
    }
  }
}
</script>
<style lang="stylus" scoped>
.el-dropdown-link {
	color: #3d88d6;
}
</style>
